package com.leo.apptest.activity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;

import com.leo.apptest.R;

public class BitmapActivity extends AppCompatActivity {

    private ImageView mIvBeforeCompress;
    private ImageView mIvAfterCompress;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bitmap);
        mIvBeforeCompress = (ImageView) findViewById(R.id.ivBeforeCompress);
        mIvAfterCompress = (ImageView) findViewById(R.id.ivAfterCompress);
        mIvBeforeCompress.setImageBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.ic_pic));
        mIvAfterCompress.setImageBitmap(compressBitmap(500,16));
    }

    public Bitmap compressBitmap(int targetHei, int targetWid){
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(getResources(),R.drawable.ic_pic,options);
        int height = options.outHeight;
        int width = options.outWidth;
        options.inSampleSize = caculateSampleSize(targetHei,targetWid,height,width);
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeResource(getResources(),R.drawable.ic_pic,options);

    }

    private int caculateSampleSize(int targetHei,int targetWid ,int hei,int wid){
        int inSampleSize = 1;
        if (hei > targetHei || wid > targetWid) {
            int sampleHei = Math.round((float) hei /(float) targetHei);
            int sampleWid = Math.round((float)wid/(float)targetWid);
            inSampleSize = sampleHei > sampleWid ? sampleHei :sampleWid;
        }
        return inSampleSize;
    }
}
